package org.alino.core.shiro;

import org.alino.core.shiro.session.AlinoSessionManager;
import org.alino.core.shiro.session.SessionStatus;
import org.alino.core.utils.DateUtils;
import org.alino.core.utils.LoggerUtils;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Desc EhCache Session管理器
 * @Author by Brant
 * @Date 2017/2/8
 */
public class ShiroEhCacheSessionDao extends CachingSessionDAO {

    public ShiroEhCacheSessionDao() {
        this.setCacheManager(new AbstractCacheManager() {
            protected Cache<Serializable, Session> createCache(String name) throws CacheException {
                return new MapCache(name, new ConcurrentHashMap());
            }
        });
    }

    protected Serializable doCreate(Session session) {
        //不存在才添加。
        if(null == session.getAttribute(AlinoSessionManager.SESSION_STATUS)){
            //Session 踢出自存存储。
            SessionStatus sessionStatus = new SessionStatus();
            session.setAttribute(AlinoSessionManager.SESSION_STATUS, sessionStatus);
        }
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        return sessionId;
    }

    protected Session doReadSession(Serializable sessionId) {
        return null;
    }

    protected void doUpdate(Session session) {

    }

    protected void doDelete(Session session) {
        LoggerUtils.info(getClass(),null,"删除Session：[%s];时间：[%s]",session.getId(), DateUtils.formatDateTimeMillis(System.currentTimeMillis(),DateUtils.YYYY_MM_DD_HH_MM_SS));
    }
}
